/** 认证 */
import { defineStore } from "pinia";
import { phoneLogin } from "../request/api/mp";
import { logout as logoutApi, refreshToken as refreshTokenApi } from "../request/api/auth";
import { getActivePinia } from "pinia";
import { clearAll } from "./clear";

const KEY_RTOKEN = 'rtoken'

/**
 * 获取系统持久化的rtoken
 */
export const getPersistRToken = () => {
	return uni.getStorageSync(KEY_RTOKEN)
}

export const useAuthStore = defineStore('auth', {
	state: () => ({
		token: null,
		rtoken: null,
	}),
	actions: {
		/**
		 * 保存信息
		 * @param {Object} token
		 * @param {Object} rtoken
		 */
		hold(token, rtoken) {
			this.token = token
			this.rtoken = rtoken
			// 持久化
			uni.setStorageSync(KEY_RTOKEN, rtoken)
		},
		/**
		 * 清除信息
		 */
		clear() {
			// 移除持久化
			uni.removeStorageSync(KEY_RTOKEN)
			this.token = null
			this.rtoken = null
		},
		/**
		 * 微信电话授权登录
		 * @param {String} code 微信电话授权码
		 */
		mpPhoneLogin(code) {
			if (!code) return Promise.reject({ code: -1, message: '参数错误' })
			return phoneLogin(code).then(({ token, rtoken }) => {
				this.hold(token, rtoken)
				return Promise.resolve({ token, rtoken })
			})
		},
		/**
		 * 刷新token
		 */
		refreshToken() {
			if (!this.rtoken) return Promise.reject({ code: -1, message: '尚未授权' })
			return new Promise((resolve, reject) => {
				refreshTokenApi(this.rtoken).then(({ token, rtoken }) => {
					this.hold(token, rtoken)
					resolve({ token, rtoken })
				}).catch(({ code = -1, message = '认证失败' }) => {
					this.clear()
					reject({ code, message })
				})
			})
		},
		/**
		 * 登出
		 */
		logout() {
			return new Promise((resolve) => {
				logoutApi(this.rtoken).catch(() => {})
				clearAll()
				resolve()
			})
		}
	}
})